package com.kevin.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioServer {

    public static void main(String[] args) {
        try {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(9999));
            ssc.configureBlocking(false);
            Selector s = Selector.open();
            ssc.register(s, SelectionKey.OP_ACCEPT);
            while (true) {
                s.select();
                Set<SelectionKey> skSet = s.selectedKeys();
                Iterator<SelectionKey> iterator = skSet.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    handle(key);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handle(SelectionKey key) {
        if (key.isAcceptable()) {
            ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
            SocketChannel sc = null;
            try {
                sc = ssc.accept();
                ssc.configureBlocking(false);
                ssc.register(key.selector(),SelectionKey.OP_READ);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    sc.close();
                    ssc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (key.isReadable()) {
            SocketChannel sc = (SocketChannel)key.channel();
            ByteBuffer bb = ByteBuffer.allocate(512);
            bb.clear();
            try {
                int len = sc.read(bb);
                if (-1 != len) {
                    System.out.println(new String(bb.array(),0,len));
                }
                ByteBuffer wrap = ByteBuffer.wrap("Hello".getBytes());
                sc.write(wrap);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    sc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
